<script setup lang="ts">
import { reactive, ref } from "vue"
import { ElDrawer, ElMessage } from "element-plus"
import company from "./company.vue"
import { companyListApi, companyQuickListApi, dictDataGetListApi } from "@/api/conventional"
import { getAdminRoleListApi } from "@/api/system"
import { doSellApi } from "@/api/billv2"
import { knotsApi } from "@/api/bill"
// import { doSellApi } from "@/api/bill"
// import { doSellApi, getBillLogListApi } from "@/api/bill"
import { generateDiscount, generatePrice } from "@/utils/common"
import Decimal from "decimal.js"
import dayjs from "dayjs"

// const listLog = ref<any>([])
const companyRef = ref<any>(null)
const dialog = ref(false)
const innerDrawer = ref(false)
const loading = ref(false)
const listData = ref<any>([])
const currentDate = dayjs()
const formData = reactive<any>({
  bill_id: 0,
  recognizerDate: "",
  billNo: "",
  acceptorName: "",
  billAmount: 0,
  enter_price: 0,
  enter_discount: 0,
  enter_finally: 0,
  enter_invoicings: 2,
  enter_checks: 2,
  expirationDate: "",
  bill_back_user: "",
  out_company_id: 0,
  out_admin_id: 0,
  out_price: undefined,
  out_discount: undefined,
  out_finally: undefined,
  out_invoicings: 2,
  out_checks: 2,
  enter_time: "",
  out_time: currentDate.format("YYYY-MM-DD HH:mm:ss"),
  out_company_name: ""
})
const dismantle_money = ref<number>(0)

const form = reactive({
  is_dismantle: 1,
  dismantle_money: 0,
  billRange: 1,
  is_retreat: 1
})

const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}

const addCompany = () => {
  if (companyRef.value) {
    companyRef.value.show()
  }
}
const drawerRef = ref<InstanceType<typeof ElDrawer>>()

const onClick = async () => {
  if (formData.out_company_id == 0) {
    ElMessage.error("请选择出票客户")
    return
  }
  handleSettlement(2)
  // ElMessageBox.confirm("是否结账?", "结账", {
  //   confirmButtonText: "是",
  //   cancelButtonText: "否",
  //   type: "warning"
  // })
  //   .then(async () => {
  //     handleSettlement(1)
  //   })
  //   .catch(() => {
  //     handleSettlement(2)
  //   })

  // ElMessage.success("修改成功")
  // handleClose()
}

async function handleSettlement(value: number) {
  try {
    // 调用接口，传递结账类型（1：先结账，2：后结账）

    await doSellApi({
      inventory_id: formData.inventory_id,
      bill_id: formData.bill_id,
      out_company_id: formData.out_company_id || 0,
      out_price: formData.out_price || undefined,
      out_discount: formData.out_discount || undefined,
      out_admin_id: formData.out_admin_id || undefined,
      out_finally: formData.out_finally || undefined,
      out_time: formData.out_time || undefined,
      out_invoicings: formData.out_invoicings || 2,
      out_checks: formData.out_checks || 2,
      dismantle_money: dismantle_money.value,
      is_dismantle: 1
    })
    ElMessage.success("操作成功")
    if (value == 1) {
      await knotsApi({ company_id: formData.out_company_id.value })
    }

    handleClose()
  } catch (error) {
    ElMessage.error("操作失败，请重试")
  }
}

const handleClose = () => {
  cancelForm()
  emit("DialogClose", true)
}
const emit = defineEmits(["DialogClose"])
const cancelForm = () => {
  state.value = ""
  formData.out_company_id = 0
  formData.out_admin_id = 0
  formData.recognizerDate = ""
  formData.billNo = ""
  formData.acceptorName = ""
  formData.expirationDate = ""
  formData.out_time = ""
  formData.bill_back_user = ""
  formData.billAmount = 0
  dismantle_money.value = 0
  formData.out_price = undefined
  formData.out_discount = undefined
  formData.out_finally = undefined
  formData.out_invoicings = 2
  formData.out_checks = 2
  form.is_dismantle = 1

  form.dismantle_money = 0
  form.billRange = 1
  form.is_retreat = 1
  loading.value = false
  dialog.value = false
  innerDrawer.value = false
}

const change = () => {
  if (dismantle_money.value == 0) {
    ElMessage.error("请输入票面金额")
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }
  if (dismantle_money.value > formData.billAmount * 10000) {
    ElMessage.error("输入票面金额不能大于原票面金额")
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }

  const { finallyAmount, discountAmount } = generatePrice(
    formData.out_price,
    formData.out_finally,
    formData.out_discount,
    dismantle_money.value / 10000 + "",
    // formData.billAmount + "",
    false
  )
  formData.out_discount = discountAmount
  formData.out_finally = finallyAmount
}
//贴息费*100000/票面金额
const discountChange = () => {
  if (dismantle_money.value == 0) {
    ElMessage.error("请输入票面金额")
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }
  if (dismantle_money.value > formData.billAmount * 10000) {
    ElMessage.error("输入票面金额不能大于原票面金额")
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }
  const { price, finallyAmount } = generateDiscount(
    formData.out_price,
    formData.out_finally,
    formData.out_discount,
    dismantle_money.value / 10000 + "",
    // formData.billAmount + "",
    false
  )
  formData.out_price = price
  formData.out_finally = finallyAmount
}
const handleFinally = () => {
  if (dismantle_money.value == 0) {
    ElMessage.error("请输入票面金额")
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }
  if (dismantle_money.value > formData.billAmount * 10000) {
    ElMessage.error("输入票面金额不能大于原票面金额")
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }
  const billAmount = new Decimal(formData.billAmount).times(10000)
  const enter_finally = new Decimal(formData.out_finally || 0)
  const discountAmount = billAmount.minus(enter_finally).toNumber()
  console.log(discountAmount)
  const { price } = generateDiscount(
    formData.out_price,
    enter_finally.toNumber(),
    discountAmount,
    dismantle_money.value / 10000 + "",
    // formData.billAmount + "",
    false
  )
  formData.out_price = price
  formData.out_discount = discountAmount
}

const handleDismantleMoneyChange = () => {
  if (dismantle_money.value == 0) {
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }
  if (dismantle_money.value > formData.billAmount * 10000) {
    ElMessage.error("输入票面金额不能大于原票面金额")
    formData.out_price = 0
    formData.out_discount = 0
    formData.out_finally = 0
    return
  }

  // 如果每十万价格已填写，根据每十万价格计算
  if (formData.out_price) {
    const { finallyAmount, discountAmount } = generatePrice(
      formData.out_price,
      formData.out_finally,
      formData.out_discount,
      dismantle_money.value / 10000 + "",
      false
    )
    formData.out_discount = discountAmount
    formData.out_finally = finallyAmount
  }
  // 如果贴息价格已填写，根据贴息价格计算
  else if (formData.out_discount) {
    const { price, finallyAmount } = generateDiscount(
      formData.out_price,
      formData.out_finally,
      formData.out_discount,
      dismantle_money.value / 10000 + "",
      false
    )
    formData.out_price = price
    formData.out_finally = finallyAmount
  }
}

const state = ref("")
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  state.value = queryString
  companyListApi({
    company_name: state.value
  }).then((res) => {
    const lists = res.data
    if (lists.length == 0) {
      ElMessage.error("请先添加企业信息")
      cb([])
    } else {
      cb(lists)
    }
  })
}

const handleSelect = (item: Record<string, any>) => {
  formData.out_admin_id = item.uid
  formData.out_company_id = item.id
}

function showClick(row: any | undefined) {
  formData.inventory_id = row.inventory_id
  formData.bill_id = row.bill_id
  formData.recognizerDate = row.recognizerDate
  formData.billNo = row.billNo
  formData.acceptorName = row.acceptorName
  formData.billAmount = row.billAmount
  dismantle_money.value = row.billAmount * 10000
  formData.expirationDate = row.expirationDate
  formData.bill_back_user = row.bill_back_user
  formData.enter_price = row.enter_price
  formData.enter_discount = row.enter_discount
  formData.enter_time = row.enter_time
  formData.enter_finally = row.enter_finally
  state.value = ""
  formData.out_company_id = 0
  formData.out_admin_id = 0
  getAdminList()
  INVOICINGFun()
  checkFun()
  // getBillLogList()
  dialog.value = true
}
const formLabelWidth = "80px"
// const getBillLogList = async () => {
//   const res = await getBillLogListApi({
//     bill_id: formData.bill_id
//   })
//   listLog.value = res.data
// }

defineExpose({ showClick })

// #region 快捷设置
// 快捷设置
const quickList = ref<any[]>([])
const companyQuickList = () => {
  companyQuickListApi({}).then((res: any) => {
    quickList.value = res.data
  })
}
companyQuickList()
const handleQuick = (item: any) => {
  console.log(item)
  state.value = item.company_name
  formData.out_admin_id = item.uid
  formData.out_company_id = item.id
}
// #endregion

const invoicingList = ref<any[]>([])
const INVOICINGFun = async () => {
  const res = await dictDataGetList("COMPANY_INVOICING")
  invoicingList.value = res.data
}
const checkList = ref<any[]>([])
const checkFun = async () => {
  const res = await dictDataGetList("COMPANY_CHECK")
  checkList.value = res.data
}

const dictDataGetList = async (type: string) => {
  try {
    const res = await dictDataGetListApi({ type_code: type })
    return res
  } catch (error) {
    console.error("Error:", error)
  }
}
</script>

<template>
  <el-dialog
    ref="drawerRef"
    v-model="dialog"
    width="80%"
    title="出库/拆分"
    :before-close="handleClose"
    class="demo-drawer"
  >
    <div class="heads">
      <el-button type="primary" text @click="addCompany">添加企业信息</el-button>
    </div>
    <div class="demo-drawer__content">
      <div class="row">
        <div class="block">
          <span class="block_title">先款先票：</span>
          <el-radio-group v-model="formData.out_checks">
            <el-radio v-for="option in checkList" :key="option.data_value" :label="Number(option.data_value)">
              {{ option.data_name }}
            </el-radio>
          </el-radio-group>
        </div>
        <div class="block">
          <span class="block_title">开票：</span>
          <el-radio-group v-model="formData.out_invoicings">
            <el-radio v-for="option in invoicingList" :key="option.data_value" :label="Number(option.data_value)">
              {{ option.data_name }}
            </el-radio>
          </el-radio-group>
        </div>
        <div class="block">
          <span class="block_title">出库时间：</span>
          <el-date-picker
            v-model="formData.out_time"
            style="width: 100%"
            type="datetime"
            placeholder="请选择出库时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
      </div>
      <el-descriptions title="票据信息" border size="small" :column="3">
        <template #extra>
          <template class="quicks">
            <div v-for="(item, index) in quickList" :key="index" class="quicks-item">
              <el-button type="primary" plain @click="handleQuick(item)">{{ item.company_name }}</el-button>
            </div>
          </template>
          <div style="display: flex; align-items: center; justify-content: space-between">
            <div style="display: flex; margin-right: 30px">
              <el-text class="mx-1" type="primary">出票客户：</el-text>
              <el-autocomplete
                v-model="state"
                value-key="company_name"
                :fetch-suggestions="querySearchAsync"
                placeholder="请选择客户"
                @select="handleSelect"
              />
            </div>
            <div style="display: flex">
              <el-text class="mx-1" type="primary">业务员：</el-text>
              <el-select v-model="formData.out_admin_id" class="m-2" placeholder="请选择">
                <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
              </el-select>
            </div>
          </div>
        </template>

        <el-descriptions-item label="日期">{{ formData.recognizerDate }}</el-descriptions-item>
        <el-descriptions-item label="票号">{{ formData.billNo }}</el-descriptions-item>
        <el-descriptions-item label="承兑人">{{ formData.acceptorName }}</el-descriptions-item>
        <el-descriptions-item label="到期日">{{ formData.expirationDate }}</el-descriptions-item>
        <el-descriptions-item label="背书人">{{ formData.bill_back_user }}</el-descriptions-item>
        <el-descriptions-item label="票面金额(万元)/(元)">
          <span>{{ formData.billAmount }}</span
          ><span style="margin-left: 5px">/</span
          ><el-input
            v-model="dismantle_money"
            type="number"
            min="1"
            placeholder="请输入"
            style="display: inline-block; width: auto; margin-left: 5px"
            @input="handleDismantleMoneyChange"
          />
        </el-descriptions-item>
        <el-descriptions-item label="每十万价格">
          <el-input v-model="formData.out_price" type="number" min="1" placeholder="请输入" clearable @input="change" />
        </el-descriptions-item>
        <el-descriptions-item label="贴息价格">
          <el-input
            v-model="formData.out_discount"
            type="number"
            min="1"
            placeholder="请输入"
            clearable
            @input="discountChange"
          />
        </el-descriptions-item>
        <el-descriptions-item label="实收金额">
          <el-input
            v-model="formData.out_finally"
            type="number"
            min="1"
            placeholder="请输入"
            clearable
            @input="handleFinally"
          />
        </el-descriptions-item>
        <!-- <el-descriptions-item label="最终价格">{{ formData.out_finally }}</el-descriptions-item> -->
      </el-descriptions>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">关闭</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">提交</el-button>
      </div>
    </div>
    <!-- <div class="logBox">
      <el-timeline>
        <el-timeline-item v-for="(item, index) in listLog" :key="index" :timestamp="item.create_time" placement="top">
          <el-card>
            <p>{{ item.user_text + item.content }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div> -->
    <el-dialog v-model="innerDrawer" width="30%" title="出库" :append-to-body="true" :before-close="handleClose">
      <div class="demo-drawer__content">
        <el-form :model="form" :label-width="formLabelWidth">
          <el-form-item label="是否拆分">
            <el-radio-group v-model="form.is_dismantle">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="2">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="拆分金额" v-if="form.is_dismantle == 2">
            <el-input-number v-model="form.dismantle_money" :min="1" :max="10" />
          </el-form-item>
          <el-form-item label="子票区间" v-if="form.is_dismantle == 2">
            <el-radio-group v-model="form.billRange">
              <el-radio :label="1">前面拆分</el-radio>
              <el-radio :label="2">后面拆分</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否退票" v-if="form.is_dismantle == 2">
            <el-radio-group v-model="form.is_retreat">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="2">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">关闭</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">提交</el-button>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
  <company ref="companyRef" />
</template>

<style scoped lang="scss">
.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.heads div {
  margin-left: 10px;
}

.demo-drawer__footer {
  margin-top: 10px;
  display: flex;
  justify-content: end;
}
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.quicks {
  display: flex;
  .quicks-item {
    margin-right: 10px;
  }
}

.row {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.block {
  width: 30%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.block_title {
  width: 100px;
}
</style>
